import { Cascader, Input, Select, SelectProps } from "antd";
import { CascaderProps } from "antd/lib/cascader";
import { useState } from "react";
import ScrollLoadSelect from "./ScrollLoadSelect";

export type PhEnhancedCascaderProps = {
  /** 是否支持自定义录入, 手动输入 */
  isManualInput?: boolean;
  /**
   * 是否只要最后一级的value（仅包括最后一个值），回填也是基于最后一个值向上查找
   */
  includeLastValueOnly?: boolean;
} & CascaderProps;

export type PhEnhancedSelectProps = {
  /** 是否支持自定义录入, 手动输入 */
  isManualInput?: boolean;
} & SelectProps;

type InternalPhEnhancedType = {};

type PhEnhancedProps = InternalPhEnhancedType & {
  /** 默认：1.支持手动录入 */
  Cascader: (data: PhEnhancedCascaderProps) => any;
  /**
   * 默认：1.支持远程+滚动分页加载，2. 支持手动录入
   * @isManualInput
   */
  Select: (data: PhEnhancedSelectProps) => any;
};

/**
 * 增强的控件
 * @param Cascader 输入选择器
 * @param Select 输入选择器
 */
const PhEnhanced: PhEnhancedProps = {} as PhEnhancedProps;

PhEnhanced.Cascader = ({
  expandTrigger = "click",
  value,
  onChange,
  allowClear = true,
}: PhEnhancedCascaderProps) => {
  const data = [{ name: "测试1", id: 1, items: [] }];
  const [inputValue, setInputValue] = useState(value);

  const handleInputChange = (e: any) => {
    const _val = e.target.value;
    setInputValue(_val);
    onChange?.(_val, []);
  };

  return (
    <Cascader
      fieldNames={{ label: "name", value: "id", children: "items" }}
      allowClear={allowClear}
      expandTrigger={expandTrigger}
      options={data || []}
      showSearch={{
        filter: (inputValue, path) => {
          return path.some(
            (option) =>
              option.name?.toLowerCase().indexOf(inputValue?.toLowerCase()) > -1
          );
        },
      }}
      onChange={(_, selectedOptions) => {
        const nameArr = selectedOptions.map((item) => item?.name);
        setInputValue(nameArr.join(" / "));
        onChange?.(nameArr, []);
      }}
    >
      <Input
        value={inputValue}
        onChange={handleInputChange}
        placeholder="请输入"
        allowClear
      />
    </Cascader>
  );
};

const list = Array.from({ length: 35 }).map((_, index) => {
  return { label: `${index}`, value: index };
});

PhEnhanced.Select = () => {
  return 111;
  const [disabledValues, setDisabledValues] = useState<any[]>([]);
  return (
    <>
      <div onClick={() => setDisabledValues((pre) => [...pre, pre.length + 1])}>
        禁用
      </div>
      <ScrollLoadSelect
        style={{ width: 200 }}
        searchName="test"
        mode="multiple"
        allowClear
        disabledValues={disabledValues}
        request={({ size, page, ...rest }) => {
          console.log("rest:", rest);
          return new Promise((resolve) => {
            setTimeout(() => {
              resolve({
                total: list.length,
                records: list.slice((page - 1) * size, page * size),
              });
            }, 800);
          });
        }}
      />
    </>
  );
};

export default PhEnhanced;
